package com.nci.cloud.unit.management.ProtoBufFileTrans;

import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.nci.cloud.unit.management.message.Message;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Future;

public class FileRecvUtils {
    final static int PARTITIONSIZE =1* 1024*1024; // 1M 大小一个包
    private static SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD hh:mm:ss");
    static Table<String,String, AsynchronousFileChannel> userFileChannelTable = HashBasedTable.create();
    String fileRecvPath;

    public FileRecvUtils(String fileRecvPath){
        if(fileRecvPath.endsWith(File.separator))
            this.fileRecvPath = fileRecvPath;
        else
            this.fileRecvPath = fileRecvPath+File.separator;
    }

    public void recvFile( Message.TransRequest req) throws IOException {
        // user validation
        String userName = req.getUser();
        String passwd = req.getPasswd();

        Date recvtime = new Date(req.getTimestamp());
        String timeString = sdf.format(recvtime);

        String fileName = req.getContent().getFilename();
        int partition = req.getContent().getPartition();
        System.out.println("recv time :"+timeString +" "+partition);
        File aExe = null;

        AsynchronousFileChannel fileChannel = null;
        if (partition == 1) {
            aExe = new File(this.fileRecvPath+ fileName);
            if (!aExe.exists()) {
                aExe.createNewFile();
            }// if
            Path path = Paths.get(aExe.getAbsolutePath());
            fileChannel =
                    AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);
            userFileChannelTable.put(userName,fileName,fileChannel);
        } //
        else{
            fileChannel = userFileChannelTable.get(userName,fileName);
        }


        ByteBuffer buffer = ByteBuffer.allocate( (int)req.getContent().getPartitionSize());
        long position = (partition-1)*PARTITIONSIZE;

        buffer.put(req.getContent().getFileContent().toByteArray());
        buffer.flip();

        Future<Integer> operation = fileChannel.write(buffer, position);
        buffer.clear();

        while(!operation.isDone());

        if (req.getContent().getPartition() == req.getContent().getPartitionNum()) {
            System.out.println("File recv success");
            fileChannel.close();
            // remove the file channel
            userFileChannelTable.remove(userName,fileName);
        }// if

    }// recvFile

}
